package com.luo.d3s.ec.infrastructure.database.convertor;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luo.d3s.core.application.dto.PageQuery;
import com.luo.d3s.core.application.dto.PageResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Page分页参数转换
 *
 * @author luohq
 * @date 2022-12-21 11:35
 */
public class PageConvertor {

    public static Page toPage(PageQuery pageQuery) {
        //特殊处理pageSize，在MybatisPlus分页插件中支持pageSize<0则取消分页，
        //扩展支持pageSize==0时自动转换为pageSize<0，即统一转换为-1
        //https://baomidou.com/pages/97710a/#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84-mapper-method-%E4%BD%BF%E7%94%A8%E5%88%86%E9%A1%B5
        Integer pageSize = (0 < pageQuery.getPageSize() ? pageQuery.getPageSize() : -1);
        Page page = Page.of(pageQuery.getPageIndex(), pageSize);
        if (StringUtils.hasText(pageQuery.getOrderBy())) {
            OrderItem orderItem = PageQuery.ASC.equals(pageQuery.getOrderDirection())
                    ? OrderItem.asc(pageQuery.getOrderBy())
                    : OrderItem.desc(pageQuery.getOrderBy());
            page.addOrder(orderItem);
        }
        return page;
    }

    public static <T> PageResponse<T> toPageResponse(IPage<T> pageResult) {
        return PageResponse.of(pageResult.getRecords(),
                Long.valueOf(pageResult.getTotal()).intValue(),
                Long.valueOf(pageResult.getCurrent()).intValue(),
                Long.valueOf(pageResult.getSize()).intValue());
    }

    public static <T, R> PageResponse<R> toPageResponse(IPage<T> pageResult, Function<T, R> convertor) {
        List<R> resultList = null;
        if (!CollectionUtils.isEmpty(pageResult.getRecords())) {
            resultList = pageResult.getRecords().stream()
                    .map(convertor)
                    .collect(Collectors.toList());
        }
        return PageResponse.of(resultList,
                Long.valueOf(pageResult.getTotal()).intValue(),
                Long.valueOf(pageResult.getCurrent()).intValue(),
                Long.valueOf(pageResult.getSize()).intValue());
    }
}
